package 链表;

/**
 * 给定一个**排序**链表，删除所有重复的元素，使得每个元素只出现一次。
 * <p>
 * 示例1:
 * <p>
 * 输入: 1->1->2
 * 输出: 1->2
 * 示例2:
 * <p>
 * 输入: 1->1->2->3->3
 * 输出: 1->2->3
 * <p>
 * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
 */
public class _83_删除排序链表中的重复元素 {
    public static void main(String[] args) {
        ListNode first = new ListNode(1);
        ListNode second = new ListNode(1);
        ListNode third = new ListNode(2);
        ListNode four = new ListNode(2);
        ListNode five = new ListNode(3);
        first.next = second;
        second.next = third;
        third.next = four;
        four.next = five;
        LinkedListUtils.printNode(first);
        ListNode node = deleteDuplicates(first);
        LinkedListUtils.printNode(node);
    }

    /**
     * 排序链表,那从前往后遍历,只要后面的值不比前面的大,那就移除元素
     */
    public static ListNode deleteDuplicates(ListNode head) {
        ListNode cur = head;
        while (cur != null && cur.next != null) {
            if (cur.next.val == cur.val) {
                cur.next = cur.next.next;
            } else {
                cur = cur.next;
            }
        }
        return head;
    }
}
